package vip.meeet.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest2 {
    static int a1,a2;
    static CyclicBarrier barrier = new CyclicBarrier(2,new Runnable(){

        @Override
        public void run() {
            System.out.println(a1+a2);
        }
        
    });
    public static void main(String[] args) {
        
       Thread t1 = new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    for(int i=0;i<100;i++)
                        a1+=i;
                    barrier.await();
                    System.out.println(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
            
        });
        
       Thread t2 = new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    for(int i=0;i<100;i++)
                        a2+=i;
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(2);
            }
            
        });
       t1.start();
       t2.start();
//       try {
//        t1.join();
//        t2.join();
//    } catch (InterruptedException e) {
//        e.printStackTrace();
//    }
       
        
//        printInfo();
//        barrier.reset();
//        printInfo();
        
    }
    
    static void printInfo(){
        System.out.println(barrier.getNumberWaiting());
        System.out.println(barrier.getParties());
        System.out.println(barrier.isBroken());
    }

}
